package com.rfid.assistant.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.rfid.assistant.R;
import com.rfid.assistant.activity.adapter.OnItemClickListener;
import com.rfid.assistant.activity.adapter.UdpAdapter;
import com.rfid.assistant.activity.adapter.WlanDeviceAdapter;
import com.rfid.assistant.bean.Machine;
import com.rfid.sockethelper.ClientManager;
import com.rfid.sockethelper.ClientSocketHelper;
import com.rfid.sockethelper.SocketBase;
import com.rfid.udp.UdpListener;
import com.rfid.udp.UdpManager;
import com.rfid.wlandirectlib.WifiDirectManager;

import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;

import javax.crypto.Mac;

import butterknife.BindView;
import butterknife.ButterKnife;

public class UdpActivity extends AppCompatActivity implements OnItemClickListener, SocketBase.OnReceiveListener {

    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.device)
    TextView mDeviceText;
    private List<Machine> mMachines;
    private UdpAdapter mUdpAdapter;
    private boolean isSend;

    public static void startActivity(Context context,boolean send) {
        Intent intent = new Intent();
        intent.putExtra("send",send);
        intent.setClass(context,UdpActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_udp_layout);
        ButterKnife.bind(this);
        isSend = getIntent().getBooleanExtra("send",false);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
        mMachines = new ArrayList<>();
        mUdpAdapter = new UdpAdapter(mMachines);
        mUdpAdapter.setListener(this);
        mRecyclerView.setAdapter(mUdpAdapter);
        try {
            UdpManager.getInstance().listening(new UdpListener() {
                @Override
                public void onReceived(String name,String pinfo, String ip) {
                    for (Machine machine:mMachines) {
                        if (machine.getIp().equals(ip)) {
                            return;
                        }
                    }
                    postUiThead(name,ip);
                }
            });
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    private void postUiThead(String name, String ip) {
        mRecyclerView.post(new Runnable() {
            @Override
            public void run() {
                Machine machine = new Machine();
                machine.setName(name);
                machine.setIp(ip);
                machine.setStatus(ClientManager.getManager().getStatus(ip));
                mMachines.add(machine);
                mUdpAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        ClientManager.getManager().addListener(this);
        mMachines.clear();
        mUdpAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onStop() {
        super.onStop();
        ClientManager.getManager().removeListener(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        UdpManager.getInstance().destroy();
    }

    @Override
    public void onClick(int pos) {
        Machine machine = mMachines.get(pos);
        if (machine.getStatus() == ClientManager.STATUS_NORMAL) {
            ClientManager.getManager().postConnect(machine.getIp());
        } else if (machine.getStatus() == ClientManager.STATUS_CONNECTED) {
            ClientSocketHelper helper = ClientManager.getManager().getClient(machine.getIp());
            if (helper != null) {
                Intent intent = getIntent();
                String action = intent.getAction();
                System.out.println("---------------");
                System.out.println(intent);
                if (Intent.ACTION_SEND.equals(action) || isSend) {
                    Uri uri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
                    SendActivity.startActivity(this,uri,helper.getServerIP());
                    return;
                }
                SafeDoorConfigActivity.startActivity(this,machine.getIp());
            }
        }
    }

    @Override
    public void onReceived(String ip, short cmd, CharSequence... text) {

    }

    @Override
    public void onConnect(String ip, boolean connect) {
        System.out.println("onConnect " + ip + ",connect = " + connect);
        mDeviceText.setText("通道建立" + (connect?"成功:":"失败:") + ip);
        for (Machine machine:mMachines) {
            if (ip.equals(machine.getIp())) {
                if (connect) {
                    machine.setStatus(ClientManager.STATUS_CONNECTED);
                    Intent intent = getIntent();
                    System.out.println("intent = " + intent);
                    String action = intent.getAction();
                    Uri uri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
                    if (uri == null) {
                        uri = intent.getData();
                    }
                    if (uri != null || isSend) {
                        SendActivity.startActivity(this,uri,ip);
                        return;
                    }
                    SafeDoorConfigActivity.startActivity(this,machine.getIp());
                } else {
                    mMachines.remove(machine);
                }
                mUdpAdapter.notifyDataSetChanged();
                return;
            }
        }
    }
}
